import { User } from "server/models/User";
import { FileModel } from "server/models/File";
import {
  successResponse,
  errorResponse,
  validationErrorResponse,
} from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { username, email, password, nickname, avatar, bio, role, status } =
      body;

    // 验证必填字段
    if (!username || !email || !password) {
      return validationErrorResponse("用户名、邮箱和密码不能为空");
    }

    if (username.length < 3 || username.length > 20) {
      return validationErrorResponse("用户名长度必须在3-20个字符之间");
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return validationErrorResponse("请输入有效的邮箱地址");
    }

    if (password.length < 6) {
      return validationErrorResponse("密码长度不能少于6位");
    }

    try {
      // 处理头像字段
      if (avatar !== null && avatar !== undefined) {
        if (typeof avatar === "number") {
          // 验证文件是否存在
          const avatarFile = await FileModel.findById(avatar);
          if (!avatarFile) {
            return validationErrorResponse("头像文件不存在");
          }
        } else if (typeof avatar === "string" && avatar !== "") {
          // 兼容旧的字符串URL格式
          return validationErrorResponse("头像格式错误，请使用文件ID");
        }
      }

      const userId = await User.createUser({
        username,
        email,
        password,
        nickname,
        avatar,
        bio,
        role: role || "user",
        status: status || "active",
      });

      return successResponse({ id: userId }, "用户创建成功");
    } catch (dbError) {
      console.warn("数据库操作失败:", dbError);
      return errorResponse(
        "创建用户失败",
        dbError instanceof Error ? dbError.message : "数据库操作失败"
      );
    }
  } catch (error) {
    console.error("创建用户失败:", error);
    return errorResponse(
      "创建用户失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
